package org.ikross.h2.adapters.dbf;

import java.sql.SQLException;

import org.h2.index.ExternCursor;
import org.h2.message.Message;
import org.h2.result.Row;
import org.h2.table.Column;
import org.h2.table.TableExtern;
import org.h2.table.TableExternAdapter;
import org.h2.value.Value;

import com.linuxense.javadbf.DBFException;
import com.linuxense.javadbf.DBFFileManager;

public class CursorDBF implements ExternCursor {
	
	private TableExtern tableExtern;
	private DBFFileManager dbfFM;
	
	private Row current;
	
	public CursorDBF(TableExtern tableExtern, DBFFileManager dbfFM){
		this.tableExtern=tableExtern;
		this.dbfFM=dbfFM;
		
		this.current=null;
	}

	public Row get() throws SQLException {
		// TODO Auto-generated method stub
		return this.current;
	}

	public int getPos() {
		// TODO Auto-generated method stub
		try {
			return this.dbfFM.getPos();
		} catch (DBFException e) {
			return -1;
		}
	}

	public boolean next() throws SQLException {
		// TODO Auto-generated method stub
		try {
			Comparable[] comparables;
			if((comparables=this.dbfFM.nextRecord())==null){
				this.current=null;
				this.dbfFM.close();
				this.dbfFM=null;
				return false;
			}
			current=this.tableExtern.getTemplateRow();
			Value[] values=new Value[comparables.length];
			Column[] columns=this.tableExtern.getColumns();
			for(int i=0;i<values.length;i++){
				values[i]=TableExternAdapter.getValue(columns[i].getType(), comparables[i]);
				current.setValue(i, values[i]);
			}
			return true;
		} catch (DBFException e) {
			// TODO Auto-generated catch block
			throw Message.convert(e);
		}
	}

}
